﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Xml;

namespace Watermark
{
    public class WaterMarkConfig
    {
        public string isOpen = string.Empty;
        public string filePath = string.Empty;
        public int padding = 0;
        public int pos = 6;
        public int quality;
        public int transparency;
        public IList<string> contain = new List<string>();
        public IList<string> exclude = new List<string>();

        private static WaterMarkConfig instance;

        private WaterMarkConfig()
        {
            loadConfigFile();
        }

        public static WaterMarkConfig GetInstance()
        {
            if (instance == null)
            {
                instance = new WaterMarkConfig();
            }
            return instance;
        }

        private void loadConfigFile()
        {
            string configFile = HttpContext.Current.Request.ApplicationPath + "/config/watermark.config";
            XmlDocument xml = new XmlDocument();
            xml.Load(HttpContext.Current.Server.MapPath(configFile));

            XmlNode waterroot = xml.SelectSingleNode("watermark");
            this.isOpen = waterroot.Attributes["isOpen"].Value;
            this.filePath = waterroot.Attributes["filePath"].Value;
            this.padding = Convert.ToInt32(waterroot.Attributes["padding"].Value);
            this.pos = Convert.ToInt32(waterroot.Attributes["pos"].Value);
            this.quality = Convert.ToInt32(waterroot.Attributes["quality"].Value);
            this.transparency = Convert.ToInt32(waterroot.Attributes["transparency"].Value);
            foreach (XmlNode rule in waterroot.ChildNodes)
            {
                if (rule.NodeType != XmlNodeType.Comment)
                {
                    if (rule.Name.ToLower().Equals("rule"))
                    {
                        var con = rule.Attributes?["urlfrom"].Value;
                        var ex = rule.Attributes?["exclude"];
                        var isex = false;
                        if (ex != null)
                        {
                            if (ex.Value == "1")
                            {
                                isex = true;
                            }
                        }
                        if (!string.IsNullOrEmpty(con))
                        {
                            if (isex)
                            {
                                exclude.Add(con.ToLower());
                            }
                            else
                            {
                                contain.Add(con.ToLower());
                            }
                        }
                    }
                }
            }
        }
    }
}
